import * as React from "react";
import { Component } from "react";
import {
  Row,
  Col,
  Button,
  Modal,
  Spin,
  Table,
  Space,
  Typography,
  Input,
  Select,
  Form,
} from "antd";
import moment from "moment";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import { observable } from "mobx";
import { observer } from "mobx-react";
// import IconFont from "../../../../../../assets/ICON";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import {
  getFilesLineLossByName,
  addFilesLineLoss,
  deleteFilesLineLoss,
  updateFilesLineLoss,
  getBindInDevices,
  getUnBindInDevices,
  getBindOutDevices,
  getUnBindOutDevices,
  configureInDevices,
  configureOutDevices,
} from "../../../ServeApi";
import { ergodicListAddIdToKey } from "../../../../../../utils/common";
import "./index.less";

const { Text } = Typography;
const { Option } = Select;

export interface LineLossTableProps {}

export interface LineLossTableState {
  loading: boolean;
  feedloading: boolean;
  selectedRowKeys: any[];
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};
@observer
class LineLossTable extends Component<LineLossTableProps, LineLossTableState> {
  @observable dataSouce: any[] = [];
  @observable dataBindSouce: any[] = [];
  @observable
  private columns: columnsDataCLass[] = [
    {
      title: "线损对象名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "统计周期",
      dataIndex: "staCycle",
      key: "staCycle",
      render: (text: string) => {
        switch (text) {
          case "2":
            return <>日</>;
          case "3":
            return <>月</>;
          case "4":
            return <>年</>;
          default:
            return <>暂无</>;
        }
      },
    },
    {
      title: "线损对象说明",
      dataIndex: "remark",
      key: "remark",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (text: string | null) => {
        if (text) {
          return moment(text).format("YYYY-MM-DD");
        } else {
          return "暂无";
        }
      },
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.Mod = "updata";
                  this.onEdit(record);
                }}
              >
                <Text style={{ color: "#1890FF" }}>编辑</Text>
              </span>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.Meth = "in";
                  this.onFeed(record);
                }}
              >
                <Text style={{ color: "#1890FF" }}>供入</Text>
              </span>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.Meth = "out";
                  this.onFeed(record);
                }}
              >
                <Text style={{ color: "#1890FF" }}>供出</Text>
              </span>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.onDelete(record);
                }}
              >
                <Text style={{ color: "#1890FF" }}>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  private columns2: columnsDataCLass[] = [
    {
      title: "设备名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "设备地址",
      dataIndex: "devAddr",
      key: "devAddr",
    },
    {
      title: "安装地址",
      dataIndex: "installAddr",
      key: "installAddr",
    },
  ];
  state = { loading: false, feedloading: false, selectedRowKeys: [] };
  private Mod: string = "add";
  private isModalVisible: boolean = false;
  private instance: any = null;
  private initValue: any = null;
  private pageIndex: number = 1;
  private pageSize: number = 20;
  private total: number = 0;
  private pageBindIndex: number = 1;
  private pageBindSize: number = 10;
  private Bindtotal: number = 0;
  //供入供出弹窗
  private isModelInOrOutVisable: boolean = false;
  private Meth: string = "in";
  private bind: boolean = false;
  iptText: string = "";
  bound: number = 1;
  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <>
        <div className="LineLossTable">
          <div className="rowcon_body">
            <div>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  this.Mod = "add";
                  this.addMenuModal();
                }}
              >
                新增
              </Button>
            </div>
            <div className="rowcon_bottom"></div>
            <Spin spinning={this.state.loading}>
              <Table
                columns={this.columns}
                dataSource={this.dataSouce}
                pagination={{
                  pageSize: this.pageSize,
                  current: this.pageIndex,
                  total: this.total,
                  onChange: (page: number) => {
                    this.pageIndex = page;
                    // this.getPream();
                  },
                }}
              ></Table>
            </Spin>
            <Modal
              title={this.Mod === "add" ? "新增线损对象" : "编辑线损对象"}
              visible={this.isModalVisible}
              onOk={() => {
                this.handleOk();
              }}
              onCancel={() => {
                this.handleCancel();
              }}
            >
              <Form {...formItemLayout} ref={(el) => (this.instance = el)}>
                <Row>
                  <Col span={24}>
                    <Form.Item
                      label="对象名称："
                      name="name"
                      rules={[
                        {
                          required: true,
                          message: "线损对象名称必填",
                        },
                      ]}
                    >
                      <Input placeholder="请填写线损对象名称" />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      label="统计周期："
                      name="staCycle"
                      rules={[
                        {
                          required: true,
                          message: "统计周期必填",
                        },
                      ]}
                    >
                      <Select placeholder="请选择统计周期">
                        <Option value="2">日</Option>
                        <Option value="3">月</Option>
                        <Option value="4">年</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item label="说明：" name="remark">
                      <Input.TextArea />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Modal>
            <Modal
              title={this.Meth === "in" ? "供入绑定设备" : "供出绑定设备"}
              visible={this.isModelInOrOutVisable}
              okText="添加"
              okType="ghost"
              onCancel={() => {
                this.handleFeedCancel();
              }}
              footer={[
                <Button
                  key="back"
                  onClick={() => {
                    this.handleFeedCancel();
                  }}
                >
                  关闭
                </Button>,
              ]}
            >
              <div className="bare_body">
                <div className="changeType_btn d_inlineFlex">
                  <Button
                    className="left"
                    type={this.bound === 1 ? "primary" : "default"}
                    onClick={() => {
                      this.changeBound(1);
                      this.forceUpdate();
                    }}
                  >
                    已绑
                  </Button>
                  <Button
                    className="right"
                    type={this.bound === 2 ? "primary" : "default"}
                    onClick={() => {
                      this.changeBound(2);
                      this.forceUpdate();
                    }}
                  >
                    未绑
                  </Button>
                </div>
                <div className="f-right" style={{ textAlign: "right" }}>
                  <Input.Group compact>
                    <Input
                      style={{ width: "60%" }}
                      placeholder="关键字搜索"
                      onChange={(e) => {
                        this.iptText = e.target.value;
                        this.forceUpdate();
                      }}
                      value={this.iptText}
                      bordered={false}
                      prefix={
                        <SearchOutlined
                          onClick={() => {
                            this.getUnBindOutDevices(this.iptText);
                          }}
                        />
                      }
                    />
                    {this.bound === 1 ? (
                      <Button
                        type="primary"
                        onClick={() => {
                          if (this.Meth === "in") {
                            //供入
                            this.configureInDevices();
                          } else {
                            this.configureOutDevices();
                          }
                        }}
                        style={{
                          background: "#F4990D",
                          borderColor: "#F4990D",
                        }}
                      >
                        解绑
                      </Button>
                    ) : (
                      <Button
                        type="primary"
                        onClick={() => {
                          if (this.Meth === "in") {
                            //供入
                            this.configureInDevices();
                          } else {
                            this.configureOutDevices();
                          }
                        }}
                      >
                        绑定
                      </Button>
                    )}
                  </Input.Group>
                </div>
              </div>
              <Spin spinning={this.state.feedloading}>
                <Table
                  style={{ marginTop: 10 }}
                  columns={this.columns2}
                  dataSource={this.dataBindSouce}
                  rowSelection={rowSelection}
                  pagination={{
                    pageSize: this.pageBindSize,
                    total: this.Bindtotal,
                    current: this.pageBindIndex,
                    onChange: (page: number) => {
                      this.pageBindIndex = page;
                      this.getPream();
                    },
                  }}
                />
              </Spin>
            </Modal>
          </div>
        </div>
      </>
    );
  }
  componentWillMount() {
    this.getListByPage();
  }
  //
  /**被动操作 */

  //供出设备绑定弹窗取消
  handleFeedCancel() {
    this.ifFeedVisible();
    this.clearFeedModel();
  }
  clearFeedModel() {
    this.initValue = null;
    this.bound = 1;
    this.pageBindIndex = 1;
    this.pageBindSize = 10;
    this.Bindtotal = 0;
    this.setState({ selectedRowKeys: [] });
    this.iptText = "";
  }
  ifFeedVisible() {
    this.isModelInOrOutVisable = !this.isModelInOrOutVisable;
    this.forceUpdate();
  }
  //供入供出已绑未绑，条件查询判断
  getPream() {
    switch (this.Meth) {
      case "in":
        if (this.bound === 1) {
          this.getBindInDevices();
        } else {
          this.getUnBindInDevices();
        }

        break;
      case "out":
        if (this.bound === 1) {
          this.getBindOutDevices();
        } else {
          this.getUnBindOutDevices();
        }
        break;
      default:
        break;
    }
  }
  //参数处理与新增，编辑函数的参数
  setPream(item: any) {
    switch (this.Mod) {
      case "add":
        this.AddSubItem(item);
        break;
      case "updata":
        item["id"] = this.initValue["id"];
        this.EditSubItem(item);
        break;
      default:
        break;
    }
  }
  ifVisible() {
    this.isModalVisible = !this.isModalVisible;
    this.forceUpdate();
  }
  //新增菜单对话框
  addMenuModal() {
    this.ifVisible();
  }
  //清空线损对象From表单
  clearFromData() {
    this.initValue = null;
    if (this.instance) {
      const container: any = (this.instance as any) as HTMLDivElement;
      container.setFieldsValue({
        name: undefined,
        staCycle: undefined,
        remark: undefined,
      });
    }
  }
  //线损对象弹窗取消
  handleCancel() {
    this.ifVisible();
    this.clearFromData();
  }
  //线损对象弹窗确认
  handleOk() {
    let _this = this;
    const container: any = (this.instance as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        _this.setPream(res);
        _this.ifVisible();
        _this.clearFromData();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  /**主动操作 */
  //选中的设备
  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };
  //绑定，未绑定切换
  changeBound(bound: number) {
    this.bound = bound;
    this.ResetPaging();
    this.getPream(); //更新请求
    this.forceUpdate();
  }
  //重置分页
  ResetPaging() {
    this.pageBindIndex = 1;
    this.pageBindSize = 10;
    this.Bindtotal = 0;
    this.setState({ selectedRowKeys: [] });
    this.forceUpdate();
  }
  //供入供出弹窗
  onFeed(item) {
    this.initValue = item;
    this.getPream(); //更新请求
    this.ifFeedVisible();
  }
  //编辑线损对象
  onEdit(item) {
    this.initValue = item;
    this.ifVisible();
    setTimeout(() => {
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue(item);
      }
    });
  }
  //删除线损对象
  onDelete(item) {
    let pream = {
      id: item.id,
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除线损对象",
      onOk: () => {
        _this.DeleteSubItem(pream);
      },
    });
  }
  /**请求数据 */
  async getListByPage(str?: string) {
    let _this = this;
    this.setState({ loading: true });
    let pream = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      name: str ? str : "",
    };
    try {
      let res: any = await getFilesLineLossByName(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataSouce = json.data.records;
        _this.total = json.data.total;
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //新增线损对象
  async AddSubItem(item) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await addFilesLineLoss(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //编辑线损对象
  async EditSubItem(item) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await updateFilesLineLoss(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //删除线损对象
  private async DeleteSubItem(pream: { id: string }) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await deleteFilesLineLoss(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //已绑定的供入设备查询
  private async getBindInDevices(str?: string) {
    let _this = this;
    this.setState({ feedloading: true });
    let pream = {
      pageIndex: this.pageBindIndex,
      pageSize: this.pageBindSize,
      lineLossId: this.initValue["id"],
      name: str ? str : "",
    };
    try {
      let res: any = await getBindInDevices(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ feedloading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataBindSouce = ergodicListAddIdToKey(json.data.records);
        _this.Bindtotal = json.data.total;
        _this.setState({ feedloading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //未绑定的供入设备查询
  private async getUnBindInDevices(str?: string) {
    let _this = this;
    this.setState({ feedloading: true });
    let pream = {
      pageIndex: this.pageBindIndex,
      pageSize: this.pageBindSize,
      lineLossId: this.initValue["id"],
      name: str ? str : "",
    };
    try {
      let res: any = await getUnBindInDevices(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ feedloading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataBindSouce = ergodicListAddIdToKey(json.data.records);
        _this.Bindtotal = json.data.total;
        _this.setState({ feedloading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //已绑定的供出设备查询
  private async getBindOutDevices(str?: string) {
    let _this = this;
    this.setState({ feedloading: true });
    let pream = {
      pageIndex: this.pageBindIndex,
      pageSize: this.pageBindSize,
      lineLossId: this.initValue["id"],
      name: str ? str : "",
    };
    try {
      let res: any = await getBindOutDevices(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ feedloading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataBindSouce = ergodicListAddIdToKey(json.data.records);
        _this.Bindtotal = json.data.total;
        _this.setState({ feedloading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //未绑定的供出设备查询
  private async getUnBindOutDevices(str?: string) {
    let _this = this;
    this.setState({ feedloading: true });
    let pream = {
      pageIndex: this.pageBindIndex,
      pageSize: this.pageBindSize,
      lineLossId: this.initValue["id"],
      name: str ? str : "",
    };
    try {
      let res: any = await getUnBindOutDevices(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ feedloading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataBindSouce = ergodicListAddIdToKey(json.data.records);
        _this.Bindtotal = json.data.total;
        _this.setState({ feedloading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //绑定/解绑 供入设备
  private async configureInDevices() {
    let _this = this;
    this.setState({ feedloading: true });
    let pream = {
      bound: this.bound === 1 ? false : true,
      deviceIds: this.state.selectedRowKeys,
      lineLossId: this.initValue["id"],
    };
    try {
      let res: any = await configureInDevices(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);

          _this.setState({ feedloading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.ResetPaging();
        _this.getPream(); //更新请求
        _this.forceUpdate();
        _this.setState({ feedloading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //绑定/解绑 供出设备
  private async configureOutDevices() {
    let _this = this;
    this.setState({ feedloading: true });
    let pream = {
      bound: this.bound === 1 ? false : true,
      deviceIds: this.state.selectedRowKeys,
      lineLossId: this.initValue["id"],
    };
    try {
      let res: any = await configureOutDevices(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ feedloading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.ResetPaging();
        _this.getPream(); //更新请求
        _this.forceUpdate();
        _this.setState({ feedloading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
}

export default LineLossTable;
